package com.hotai.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hotai.comment.dtos.ResponseResult;
import com.hotai.comment.enums.AppHttpCodeEnum;
import com.hotai.comment.enums.AppJwtUtil;
import com.hotai.comment.md5.MD5Utils;
import com.hotai.comment.pojo.User;
import com.hotai.mapper.UserMapper;
import com.hotai.service.UserService;
import com.hotai.vo.user.LoginDto;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiecImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    private static final String Salt = "MHCDEKLDE321";

    @Override
    public ResponseResult login(LoginDto dto) {

        if( (StringUtils.isEmpty(dto.getPassword())&&StringUtils.isEmpty(dto.getPassword()))){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.手机号+密码登录
        if(!StringUtils.isEmpty(dto.getUsername())&&!StringUtils.isEmpty(dto.getPassword())){
            //用户登录
            User dbUser = userMapper.selectOne(Wrappers.<User>lambdaQuery().eq(User::getUsername, dto.getUsername()));
            if (dbUser!=null) {
                String pswd = MD5Utils.encodeWithSalt(dto.getPassword(),Salt);
                if (dbUser.getPassword().equals(pswd)) {
                    Map<String, Object> map = new HashMap<>();
                    dbUser.setPassword(pswd);
                    dbUser.setSalt("");
                    map.put("token", AppJwtUtil.getToken(dbUser.getId().longValue()));
//                    map.put("user", dbUser);
                    return ResponseResult.okResult(map);
                } else {
                    return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
                }
            } else {
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "用户不存在");
            }
        }
      return    null;

    }
}
